/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import React from 'react';
import { observer } from 'mobx-react';
import { Table, Modal, message, Tag } from 'antd';
import { Action } from 'components';
import ComForm from './Form';
import ComSync from './Sync';
import { http, hasPermission } from 'libs';
import store from './store';

@observer
class ComTable extends React.Component {
    action_name;
  componentDidMount() {
    store.fetchRecords()
  }

  handleDisable = (text, status) => {
    this.action_name = ['上线', '下线']
    Modal.confirm({
      title: `应用${this.action_name[status]}确认`,
      content: `确定要${this.action_name[status]}【${text['name']}】?`,
      onOk: () => {
        return http.options('/api/application/app/', {params: {id: text.id, status: status}})
          .then(() => {
            message.success(`应用${this.action_name[status]}成功`);
            store.fetchRecords()
          })
      }
    })
  };

  render() {
    let data = store.permRecords;
    if (store.f_name) {
      data = data.filter(item => item['name'].toLowerCase().includes(store.f_name.toLowerCase()))
    }
    if (store.f_register_id) {
      data = data.filter(item => item['register_id'] === store.f_register_id)
    }
    return (
      <React.Fragment>
        <Table
          rowKey="id"
          loading={store.isFetching}
          dataSource={data}
          pagination={{
            showSizeChanger: true,
            showLessItems: false,
            hideOnSinglePage: false,
            showTotal: total => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}>
          <Table.Column width={150} title="注册中心" dataIndex="register_id" render={(id) => store.registersMap[id] }/>
          <Table.Column width={150} title="APP" dataIndex="name" sorter={(a, b) => a.name.localeCompare(b.name)}/>
          <Table.Column width={150} title="APP地址" dataIndex="socket"/>
          <Table.Column width={100} title="APP状态" dataIndex="status" render={value => value==='UP'? <Tag color="green">{value}</Tag>:<Tag color="red">{value}</Tag>}/>
          <Table.Column width={100} ellipsis title="备注信息" dataIndex="desc"/>
          {hasPermission('application.app.disable | application.app.enable') && (
            <Table.Column width={100} title="操作" render={info => info.status === 'UP' ? (
              <Action>
                <Action.Button auth="application.app.disable" onClick={() => this.handleDisable(info, 1)}>下线</Action.Button>
              </Action>
            ): (
              <Action>
                <Action.Button auth="application.app.enable" onClick={() => this.handleDisable(info, 0)}>上线</Action.Button>
              </Action>
            )}/>
          )}
        </Table>
        {store.formVisible && <ComForm/>}
        {store.syncVisible && <ComSync/>}
      </React.Fragment>
    )
  }
}

export default ComTable
